import { Injectable, InternalServerErrorException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { GetCollectDto } from "../dto/collect.dto";
import { Goods } from "/@/entities/goods/Goods.entity";
import { Collect } from "/@/entities/operate/Collect.entity";
import { User } from "/@/entities/user/User.entity";
import { format } from "/@/utils/moment";
@Injectable()
export class CollectService {
  constructor(
    @InjectRepository(Goods)
    private goodsRepository: Repository<Goods>,
    @InjectRepository(Collect)
    private collectRepository: Repository<Collect>,
  ) {
    //
  }
  /**
   * 获取Collect列表
   * @param query 字段
   */
  async getCollectList(query: GetCollectDto) {
    const { pageSize = 10, page = 1, id, user_id, goods_id } = query;
    try {
      let qb = this.collectRepository.createQueryBuilder("collect");
      qb = qb.limit(pageSize).offset((page - 1) * pageSize); //分页查询

      if (id) {
        qb = qb.andWhere("id = :id", { id });
      }
      if (user_id) {
        qb = qb.andWhere("user_id = :user_id", { user_id });
      }
      if (goods_id) {
        qb = qb.andWhere("goods_id = :goods_id", { goods_id });
      }
      qb = qb
        .leftJoinAndSelect(Goods, "goods", "goods.id = collect.goods_id")
        .leftJoinAndSelect(User, "user", "user.id = collect.user_id")
        .select(
          `collect.id as id,
          collect.goods_id as goods_id,
          collect.update_at as update_at,
          collect.user_id as user_id,
          user.nickName as user_name,
          user.avatarUrl as user_avatar_url,
          goods.name as goods_name,
          goods.urls as urls,
          goods.name as goods_name`,
        );
      const items = await qb.getRawMany();
      items.map((item) => {
        item.urls = item.urls.split(",");
        item.user_avatar_url = item.user_avatar_url
          ? item.user_avatar_url.split(",")
          : [];
        item.update_at = format(item.update_at, "YYYY-MM-DD HH:mm:ss");
        return item;
      });
      const total = await qb.getCount();
      return { items, total };
    } catch (error) {
      console.log(error);
      throw new InternalServerErrorException("查询失败");
    }
  }
}
